package com.jsbb.service.sys;

import com.jsbb.config.ParamsConfig;
import com.jsbb.mapper.sys.SysFileMapper;
import com.jsbb.entity.sys.SysFile;
import com.jsbb.util.DateUtils;
import com.jsbb.util.IdUtils;
import com.jsbb.vo.sys.SysFileVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;

/**
 * 文件Service
 *
 * @author jsbb
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysFileService {

    @Autowired
    private ParamsConfig paramsConfig;

    @Autowired
    private SysFileMapper sysFileMapper;

    public SysFileVo upload(MultipartFile file, String module) throws Exception {
        String suffix = StringUtils.getFilenameExtension(file.getOriginalFilename());
        Long id = IdUtils.getLongId();
        String url = module + "/" + DateUtils.getCurrentDate(DateUtils.YM) + "/" + id + "." + suffix;
        File dest = new File(paramsConfig.getFilePath() + url);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        SysFile sysFile = new SysFile();
        sysFile.setId(id);
        sysFile.setModule(module);
        sysFile.setFileName(StringUtils.stripFilenameExtension(file.getOriginalFilename()));
        sysFile.setSuffix(suffix);
        sysFile.setUrl(url);
        sysFile.setFileSize(file.getSize());
        sysFile.setContentType(file.getContentType());
        sysFile.setState(1);
        sysFile.setCreateTime(LocalDateTime.now());
        sysFile.setUpdateTime(sysFile.getCreateTime());
        sysFileMapper.insert(sysFile);
        SysFileVo sysFileVo = new SysFileVo();
        BeanUtils.copyProperties(sysFile, sysFileVo);
        return sysFileVo;
    }

    public SysFileVo get(String id) {
        return null;
    }
}
